<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\api\model\v1;
use think\Model;
use think\facade\Db;

class Verify extends Model{
    /**登录验证：此处待改进，太啰嗦了
	@ accountType 账号类型：mobile手机，email邮箱，QQ，weixin微信开放平台及微信公众号，新浪微博
	@ account 账号
	@ password 尚未MD5的密码
    @ entrance 入口，admin表示登录后台
    @ result 返回error失败，数组表示成功 
	**/
	static function checkLogin($accountType='',$account='',$password='',$entrance=''){
		if(empty($accountType)){
            if(preg_match('/^1[3-9][0-9]\d{8}$/',$account)){
                $userWhere[] = ['user.mobile','=',$account];
                $userWhere[] = ['user.password','=',md5($password)];
            }elseif(filter_var($account,FILTER_VALIDATE_EMAIL)){
                $userWhere[] = ['user.email','=',$account];
                $userWhere[] = ['user.password','=',md5($password)];
            }else{
                $userWhere[] = ['user.username','=',$account];
                $userWhere[] = ['user.password','=',md5($password)];
            }
        }else{
            switch ($accountType) {
                case 'qq':
                    $userWhere[] = ['user.qqid','=',$account];
                    break;
                case 'weixin':
                    $userWhere[] = ['user.openid','=',$account];
                    break;
                case 'sina':
                    $userWhere[] = ['user.weiboid','=',$account];
                    break;
                case 'mobile':
                    $userWhere[] = ['user.mobile','=',$account];
                    $userWhere[] = ['user.password','=',md5($password)];
                    break;
                case 'email':
                    $userWhere[] = ['user.email','=',$account];
                    $userWhere[] = ['user.password','=',md5($password)];
                    break;
            }
        }
        // 登录判断
        $userRs = Db::view('user','*')
                ->view('auth_group_access','uid','auth_group_access.uid=user.id')
                ->view('auth_group','id as groupid,rules,discount,is_admin,title','auth_group.id=auth_group_access.group_id')
                ->where($userWhere)->find();
        if(empty($userRs)){
            return 'error';//账号或密码有误
        }else{//更新登录时间和登录次数
            $userid = $userRs['id']; $nickname = $userRs['nickname'];
            $data['lastlogin'] = time(); $data['logintimes'] = $userRs['logintimes'] + 1;
            // 社交类型
            if(session('?socialRs')){
                $socialRs = session('socialRs');
                switch ($socialRs['type']) {
                    case 'qq':
                        switch ($socialRs['gender']) {
                            case '男':
                                $gender = 1;
                                break;
                            case '女':
                                $gender = 2;
                                break;
                            default:
                                $gender = 0;
                                break;
                        }
                        $data['qq_unionid'] = $socialRs['unionid'];
                        $data['qqid'] = $socialRs['openid'];
                        $data['nickname'] = $socialRs['nickname'];
                        $data['gender'] = $gender;
                        $data['avatar'] = $socialRs['avatar'];
                        break;
                    case 'weixin':
                        // 注册微信开放平台才有unionid
                        // $data['wx_unionid'] = $socialRs['unionid'];
                        $data['openid'] = $socialRs['openid'];
                        $data['nickname'] = $socialRs['nickname'];
                        $data['avatar'] = $socialRs['avatar'];
                        $data['subscribe'] = 1;//此为公众号开发非微信开放平台
                        $data['gender'] = $socialRs['sex'];
                }
            }
            Db::name('user')->where('id',$userid)->update($data);
            session('userid',$userid);
            session('username',$userRs['username']);
            session('nickname',$nickname);
            session('avatar',$userRs['avatar']);
            // 会员组及权限
            $arr_rules = explode(',',$userRs['rules']);
            session('groupid',$userRs['groupid']);
            session('group_discount',$userRs['discount']);
            session('is_admin',$userRs['is_admin']);
            session('rules',$arr_rules);

            return $userRs;
        }
	}

	/**生成随机数,用于生成salt
    @ length 长度
    **/
	static function randStr($length){
		//生成一个包含：数字、小写字母、大写字母的数组
        $arr = array_merge(range(0,9), range('a','z'), range('A','Z'));
        $str = '';
        $arrLength = count($arr);
        for($i = 0; $i < $length; $i++){
            $rand = mt_rand(0, $arrLength-1);
            $str .= $arr[$rand];
        }
        return $str;
	}

	/**用户勾选"保存一月"
    @ userid 用户ID
    @ identifier 第二身份标识
    @ token MD5了的标识
    @ timeout 过期时间
    **/
	static function saveRemember($userid,$identifier,$token,$timeout){
		$data = ['identifier'=>$identifier,'token'=>$token,'timeout'=>$timeout];
        $rs = Db::name('user')->where('id',$userid)->update($data);
        return $rs;
	}

    /*账号验证
    * @accountType 账号类型：mobile手机，email邮箱，username用户名
    * @account 账号
    * @method 验证方式，reg注册，getpwd找回密码，login登录，edit编辑
    * @返回json值：success成功
    * mobile:error手机号格式错误，mobile:existed手机号已存在，mobile:notexisted手机号不存在
    * email:error邮箱格式错误，email:existed邮箱已存在，email:notexisted邮箱不存在
    */
    static function account($accountType,$account,$method){
        switch ($accountType) {
            case 'mobile':
                //手机号格式错误
                if(!preg_match('/^1[3-9][0-9]\d{8}$/',$account)){
                    return 'mobile:error';
                }
                $userRs = Db::name('user')->where('mobile',$account)->find();
                switch ($method) {
                    case 'reg':
                        //手机号已存在
                        if(!empty($userRs)) return 'mobile:existed';
                        break;
                    case 'getpwd':
                        //手机号不存在
                        if(empty($userRs)) return 'mobile:notexisted';
                        break;
                    case 'edit':
                        //手机号已存在
                        if(!empty($userRs)) return 'mobile:existed';
                        break;
                }
                break;
            case 'email':
                //邮箱格式错误
                if(!filter_var($account,FILTER_VALIDATE_EMAIL)){
                    return 'email:error';
                }
                $userRs = Db::name('user')->where('email',$account)->find();
                switch ($method) {
                    case 'reg':
                        //邮箱已存在
                        if(!empty($userRs)) return 'email:existed';
                        break;
                    case 'getpwd':
                        //邮箱不存在
                        if(empty($userRs)) return 'email:notexisted';
                        break;
                    case 'edit':
                        //邮箱已存在
                        if(!empty($userRs)) return 'email:existed';
                        break;
                }
                break;
            case 'username':
                //用户名格式错误：字母开头，纯字母或字母数字组合，4-20位为合法
                $pattern = '/^[a-z]{1}([a-z0-9]){3,19}$/';
                if(!preg_match($pattern,$account)) return 'error:username';
                switch ($method) {
                    case 'edit':
                        $userRs = Db::name('user')->where('username',$account)->find();
                        //用户名已存在
                        if(!empty($userRs)) return 'username:existed';
                        break;
                }
                break;
        }
        return 'success';
    }

    /*发送的验证码验证
    * account 账号：手机号码或邮箱
    * captcha 验证码
    * 返回值：
    * success成功，error:captcha验证码有误
    */
    static function captcha($account,$captcha){
        $logWhere[] = ['account','=',$account]; $logWhere[] = ['content','=',$captcha];
        $logWhere[] = ['signid','=',1]; $logWhere[] = ['endtime','> time',time()];
        $captchaRs = Db::name('log')->where($logWhere)->find();
        if(empty($captchaRs)) return 'error:captcha';
        return 'success';
    }
}